package com.zhentao.aop;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhentao.common.Result;
import com.zhentao.domain.SysUser;
import com.zhentao.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @ClassName: InterceptorClass
 * @Desrciption: Mr.chengfenzhan
 * @Author: 知安_程烽展
 * @Date: 2024/9/3 9:59
 */
@Component
public class InterceptorClass implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redis;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求方式
        String method = request.getMethod();
        if("OPTIONS".equals(method)) {      // 如果是跨域预检请求，直接放行
            return true ;
        }
        String token = request.getHeader("Authorization");
        if(StringUtils.checkValNull(token)){
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(JSON.toJSON(Result.build(null, 500, "请先登录")));
            return false;
        }

        String data = redis.opsForValue().get("login:token:" + token);
        if (StringUtils.isBlank(data)){
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(JSON.toJSON(Result.build(null, 500, "登录过期")));
            return false;
    }

        SysUser sysUser = JSON.parseObject(data, SysUser.class);
        ThreadLocalUtil.set(sysUser);
        return true;
    }
}
